#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-09-11 21:26:07
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$
import os
import conf,db
import requests
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


class Message(object):
    """docstring for Message"""

    def __init__(self, mess_info=conf.message_info):
        self.login_url = mess_info.get('login_url')
        self.query_url = mess_info.get('query_url')
        self.user = mess_info.get('user')
        self.passwd = mess_info.get('passwd')
        self.smsbao_code = {
            30 : '密码错误',
            40 : '账号不存在',
            41 : '余额不足',
            42 : '帐号过期',
            43 : 'IP地址限制',
            50 : '内容含有敏感词',
            51 : '手机号码不正确',
            -1 : '参数不全'
        }

    # 短信发送

    def mess_send(self, phone, content):
        payload = {
            'u': self.user,
            'p': self.passwd,
            'm': phone,
            'c': content
        }

        try:
            r = requests.get(self.login_url, params=payload) #get请求发送短信
            code_r = r.text
            code = int(code_r)
            if code_r.isdigit(): #判断返回码是否为数字
                if not code:
                    result = {
                        'code': 0000,
                        'message': '短信发送成功',
                        'data': {
                            'phone': phone,
                            'content': content
                        }
                    }
                    #return result
                else:
                    result = {
                        'code': 2001,
                        'message' : self.smsbao_code.get(code)
                    }
                    #return result
            elif code_r == '-1':
                result = {
                    'code': 2002,
                    'message': conf._code.get('2002', '参数不全')
                }
                #return result
            else:
                result = {
                    'code': 2003,
                    'message': conf._code.get('2003', '短信发送失败')
                }

            try:
                if not result['code']:
                    status = 1
                else:
                    status = 0

                wtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #获取当前本地时间
                resu = self.log_message(phone,content,wtime,status) #发送短信写入日志
                if resu == 1:
                    result['log'] = True
                    result['log_mess'] = resu
                else:
                    result['log'] = False
                    result['log_mess'] = resu

                return result
            except Exception, e:
                result = {
                    'code' : 2006,
                    'message' : str(e)
                }
                return result


        except Exception, e:
            #raise e
            result = {
                'code': 2004,
                'message': str(e)
            }
            return result

    # 短信使用情况
    def query_mess(self):
        payload = {
            'u': self.user,
            'p': self.passwd,
        }
        try:
            r = requests.get(self.query_url,params=payload)
            code_r = r.text
            if code_r.isdigit():
                code = int(code_r)
                result = {
                    'code' : 2005,
                    'message' : self.smsbao_code.get(code)
                }
                return result
            elif code_r == '-1':
                result = {
                    'code': 2002,
                    'message': conf._code.get('2002', '参数不全')
                }
                return result
            else:
                status,data = code_r.split()   #返回成功信息并分组,status返回成功状态0
                data = data.split(',')
                data = [int(data[0]),int(data[1])]  #接收参数，发送条数，剩余条数
                result = {
                    'code' : 0,
                    'message' : '查询成功',
                    'result' : {
                        'data' : data
                    }
                }
                return result

        except Exception, e:
            #raise e
            result = {
                'code' : 2005,
                'message' : str(e)
            }
            return result

    # 上课通知

    def notify(self,ntime,class_type,class_num,class_content):
        content = '【京峰课堂】尊敬的{nickName}:我们将于{ntime}进行{class_type}上课，上课内容为[{class_content}],请准时上课。'
        result = {
            'code' : 0000,
            'message' : 'success'
        }
        query = '''SELECT phone,nickName FROM user
                    WHERE class_type="{class_type}" AND class_num="{class_num}"
                '''.format(class_type=class_type,class_num=class_num) #查询用户手机号，名字
        try:
            datas = db.db_select_all(query)
            #如果查询异常，except抛出异常，异常原因为{'message': 'need more than 1 value to unpack', 'code': 2007}
            if datas:
                for phone,nickName in datas:
                    contents =content.format(
                                    nickName=nickName,
                                    ntime=ntime,
                                    class_type=class_type,
                                    class_content=class_content)
                    resu = self.mess_send(phone=phone,content=contents)
                    #print 'resu:',resu['code'],resu['message'],resu['data']['content']
                    result[phone] = resu
                return result
            else:
                result = {
                    'code' : 2008,
                    'message' : conf._code.get(2008,'查询条件不符')
                }
                return result
        except Exception, e:
            #raise e
            result = {
                'code' : 2007,
                'message' : str(e)
            }
            return result



    # 获取短信日志
    def log_info(self,table,*fields,**conditions):
        self.query = self.get_sql(table,*fields,**conditions)
        try:
            data = db.db_select_all(self.query)
            result = {
                'code' : 0000,
                'message' : conf._code.get(0000),
                'data' : data
            }
            return result
        except Exception, e:
            #raise e
            result = {
                'code' : 2007,
                'message' : str(e)
            }
            return result


    # 短信发送日志写入
    def log_message(self,phone,content,wtime,status):
        query = 'INSERT INTO message_log(phone,content,wtime,STATUS) \
            VALUES({phone},"{content}","{wtime}",{status});'.format(
                phone=phone,content=content,wtime=wtime,status=status)
        status = db.db_insert_on(query) #插入数据库，成功1，失败None,异常 str(e)
        return status

    #多条件查询语句组合
    def get_sql(self,table,*fields,**conditions):
        if not fields :
            fields=('*')
        self.sql = 'SELECT %s FROM %s' % (','.join(fields),table)
        if conditions:
            if 'start_wtime' in conditions.keys() or 'end_wtime' in conditions.keys():

                if 'start_wtime' in conditions.keys():
                    start_date = conditions['start_wtime'] + ' 00:00:00'
                    del(conditions['start_wtime'])
                else:
                    start_date=time.strftime("%Y-%m-%d", time.localtime()) + ' 00:00:00'
                if 'end_wtime' in conditions.keys():
                    end_date = conditions['end_wtime'] + ' 23:59:59'
                    del(conditions['end_wtime'])
                else:
                    end_date = time.strftime("%Y-%m-%d", time.localtime()) + ' 23:59:59'

                self.sql += ' WHERE ' + ' AND '.join(map(lambda x: '%s="%s"' % (x,conditions[x]),conditions))
                self.sql += ' AND wtime BETWEEN "{start_date}"  AND  "{end_date}" '.format(start_date=start_date,end_date=end_date)
                return self.sql

            #如果conditions为真，通过map和lambda组合查询条件
            #map(function, sequence[, sequence, ...]) -> list
            #通过定义可以看到，这个函数的第一个参数是一个函数，剩下的参数是一个或多个序列，返回值是一个集合。
            #map(lambda x: x ** 2, [1, 2, 3, 4, 5])
            self.sql += ' WHERE ' + ' AND '.join(map(lambda x: '%s="%s"' % (x,conditions[x]),conditions))
        return self.sql


if __name__ == '__main__':

    m = Message()
    #发送短信
    # mess = m.mess_send('13720027400','今天晚上吃什么呀,吃火锅吧!')
    # print mess
    # print mess['code'],mess['message']

    #查询短信使用情况
    mess = m.query_mess()
    if mess['code'] == 0:
        print mess['code'],mess['message'],mess['result']['data']
    else:
        print mess['code'],mess['message']

    #获取短信日志
    # fields=('*')
    # conditions={
    #     'phone' : '13720027400',
    #     'status' : '1',
    #     'start_wtime' : '2016-09-23',
    #     'end_wtime' : '2016-09-26'
    # }
    # print m.log_info('message_log')

    #notify(self,ntime,class_type,class_num,class_content)
    # mess = m.notify('8','python','1','iPhone 7 plus')
    # for k,v in mess.items():
    #     print k,v
